// pages/mine/shopCart/shopCart.js
var app = getApp();
import Api from '../../../api/api.js';
const api = new Api();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    isEmpty: false,
    isSelectedAll: false,
    totalPrice: "0.00",
    totalCount: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getListData();
  },
  getListData() {
    var _this = this;
    var map = {};
    map.type = "5";
    map.appId = app.APP_ID;
    map.userId = app.USER_ID();

    api.getRequestData(app.shopCartListUrl, map, true, "POST").then(res => {
      if (res.data.errorCode == 0) {
        var list = res.data.model.list;
        console.log(JSON.stringify(list[0]));
        for (var i = 0; i < list.length; i++) {
          var dict = list[i];
          dict.isSelected = 0;
        }
        console.log(JSON.stringify(list[0]));
        _this.data.dataList = list;
        _this.setData({
          dataList: _this.data.dataList
        });
        if (_this.data.dataList.length == 0) {
          _this.setData({
            isEmpty: true
          });
        } else {
          _this.setData({
            isEmpty: false
          });
        }
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  subCountClick(e) {
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.dataList[index];
    var count = parseInt(dict.qty);
    if (count - 1 <= 0) {
      count = 1;
      app.alert("购买数量不能是0呀~");
    } else {
      count -= 1;
    }
    dict.qty = count;
    this.setData({
      dataList: this.data.dataList
    });
    this.showTaotalPrice();
  },
  addCountClick(e) {
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.dataList[index];
    var count = parseInt(dict.qty);
    if (count + 1 >= 100) {
      count = 99;
      app.alert("购买数量不能超过99呀~");
    } else {
      count += 1;
    }
    dict.qty = count;
    this.setData({
      dataList: this.data.dataList
    });
    this.showTaotalPrice();
    this.checkIsAllSelected();
    this.updateCartClick(dict);
  },
  rowSelectedClick(e) {
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.dataList[index];
    if (dict.isSelected == 1) {
      dict.isSelected = 0;
    } else {
      dict.isSelected = 1;
    }
    console.log(dict.isSelected);
    this.setData({
      dataList: this.data.dataList
    });
    this.showTaotalPrice();
    this.checkIsAllSelected();
    // this.updateCartClick(dict);
  },
  allClick() {
    if (this.data.isSelectedAll) {
      this.data.isSelectedAll = false;
    } else {
      this.data.isSelectedAll = true;
    }
    for (var i = 0; i < this.data.dataList.length; i++) {
      var dict = this.data.dataList[i];
      if (this.data.isSelectedAll) {
        dict.isSelected = 1;
      } else {
        dict.isSelected = 0;
      }
    }
    this.setData({
      isSelectedAll: this.data.isSelectedAll,
      dataList: this.data.dataList
    });
    this.showTaotalPrice();
  },
  checkIsAllSelected(){
    var isAll = true;
    for (var i = 0; i < this.data.dataList.length; i++) {
      var dict = this.data.dataList[i];
      if (dict.isSelected == 0){
        isAll = false;
        break;
      }
    }
    this.setData({
      isSelectedAll:isAll
    });
  },
  showTaotalPrice(e) {
    var map = this.getTotalPrice();
    this.setData({
      totalPrice: map.totalPrice,
      totalCount: map.totalCount
    });
  },
  getTotalPrice() {
    var totalPrice = 0;
    var totalCount = 0;
    for (var i = 0; i < this.data.dataList.length; i++) {
      var dict = this.data.dataList[i];
      if (dict.isSelected == 1) {
        var count = parseInt(dict.qty + "");
        var pirce = parseFloat(dict.salePrice + "");
        totalPrice += count * pirce;
        totalCount += count;
      }
    }
    var map = {};
    map.totalPrice = totalPrice.toFixed(2);
    map.totalCount = totalCount;
    return map;
  },
  goToCreatePage() {
    if (this.data.totalCount == 0) {
      app.alert("请选中要结算的商品~");
      return;
    }
    var list = [];
    console.log(JSON.stringify(this.data.dataList));
    var contentId = '';
    for (var i = 0; i < this.data.dataList.length; i++) {
      var dic = this.data.dataList[i];
      if (dic.isSelected == 1) {
        dic.selectCount = dic.qty;
        contentId = dic.contentId;
        list.push(dic);
      }
    }
    var listString = JSON.stringify(list);
    wx.setStorageSync("payList", listString);
    app.ORDER_TYPE = "5";
    var url = '/pages/index/createOrder/createOrder?postId=' +contentId;
    wx.navigateTo({
      url: url,
    })
  },

  updateCartClick(dict){
    var _this = this;
    var map = {};
    map.id = dict.carId;
    map.productId =  dict.productId;
    if (dict.contentId){
      map.contentId = dict.contentId;
    }
    map.qty = dict.qty;
    map.skuId = dict.skuId;
    map.type = "5";
    map.userId = app.USER_ID();;

    api.getRequestData(app.updateCartUrl, map, true, "POST").then(res => {
      if (res.data.errorCode == 0) {
        console.log("更新购车成功。。。。。。");
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  beginDelete(e){
    var _this = this;
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.dataList[index];
    wx.showModal({
      title: '提示',
      content: '确定要删除这个商品吗?',
      confirmText:"确定删除",
      confirmColor:"red",
      success: function (res) {
        if (res.confirm) {
           _this.deleteCartClick(dict);
        } else if (res.cancel) {
        }
      }
    });
  },

  deleteCartClick(dict){
    var _this = this;
    var map = {};
    map.id = dict.carId;
    if (dict.contentId){
      map.contentId = dict.contentId;
    }
    api.getRequestData(app.deleteCartUrl, map, true, "GET").then(res => {
      if (res.data.errorCode == 0) {
       app.alert("删除成功~");
       setTimeout(function(){
         _this.getListData();
         _this.updateCartClick();
       },1400);
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})